package com.galaxy.commom.base.resolver;

import com.galaxy.commom.base.annotation.JwtClaim;
import com.galaxy.commom.base.exception.RequestException;
import com.galaxy.commom.base.message.ResponseCode;
import com.galaxy.commom.base.utils.JwtUtil;
import java.lang.annotation.Annotation;
import javax.servlet.http.HttpServletRequest;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * jwtToken参数解释器实现
 * @author caijinbang
 * @date 2018/10/28 15:09
 */
public class JwtTokenArgumentResolver implements HandlerMethodArgumentResolver {

  /**
   * 支持参数
   * @param parameter
   * @return
   */
  @Override
  public boolean supportsParameter(MethodParameter parameter) {
    return parameter.hasParameterAnnotation(JwtClaim.class);
  }

  /**
   * 参数解析
   * @param parameter
   * @param mavContainer
   * @param webRequest
   * @param binderFactory
   * @return
   * @throws Exception
   */
  @Override
  public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
    HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
    String authorization = request.getHeader("Authorization");
    String result = null;
    JwtClaim token = null;
    if(authorization!=null){
      Annotation[] methodAnnotations = parameter.getParameterAnnotations();
      for (Annotation methodAnnotation : methodAnnotations) {
        if(methodAnnotation instanceof JwtClaim){
          token = (JwtClaim) methodAnnotation;
          break;
        }
      }
      if(token!=null){
        result = JwtUtil.get(authorization,token.value());
      }
    }
    if(result!=null){
      return result;
    }
    if(token==null || token.exception()){
      throw new RequestException(ResponseCode.NOT_SING_IN);
    }else{
      return null;
    }
  }
}
